from flask import render_template, current_app, jsonify, request, g

from info.models import Category, News
from info.utils.response_code import RET
from . import news_blue
from info.utils.commons import login_required


@news_blue.route("/")
@login_required
def index():
    """
    项目首页
        首页右上角用户信息展示
        1. 从RIDES中获取user_id,根据user_id查询mysql,获取用户信息

    :return:
    """
    user = g.user
    try:
        categories = Category.query.all()
    except Exception as e:
        current_app.logger.errno(e)
        return jsonify(errno=RET.DBERR, errmsg="查询分类数据失败")
    if not categories:
        return jsonify(errno=RET.NODATA, errmsg="无新闻分类数据")
    category_list = []
    for category in categories:
        category_list.append(category.to_dict())
    # 新闻点击排行
    try:
        news_list = News.query.order_by(News.clicks.desc()).limit(6)
    except Exception as e:
        current_app.logger.errno(e)
        return jsonify(errno=RET.DBERR, errmsg="查询新闻排行数据失败")
    if not news_list:
        return jsonify(errno=RET.DBERR, errmsg="无新闻排行数据")
    news_click_list = []
    for news in news_list:
        news_click_list.append(news.to_dict())

    data = {
        'user_info': user.to_dict() if user else None,
        'category_list': category_list,
        'news_click_list': news_click_list
    }
    return render_template('news/index.html', data=data)


@news_blue.route("/news_list")
def get_news_list():
    cid = request.args.get('cid', '1')
    page = request.args.get('page', '1')
    per_page = request.args.get('per_page', '10')
    try:
        cid, page, per_page = int(cid), int(page), int(per_page)
    except Exception as e:
        current_app.logger.errno(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数类型错误")
    filters = []
    if cid > 1:
        filters.append(News.category_id == cid)
    try:
        paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page, per_page, False)
    except Exception as e:
        current_app.logger.errno(e)
        return jsonify(errno=RET.DBERR, errmsg="查询新闻列表数据失败")
    news_list = paginate.items
    total_page = paginate.pages
    current_page = paginate.page
    news_dict_list = []
    for news in news_list:
        news_dict_list.append(news.to_dict())

    data = {
        'news_dict_list': news_dict_list,
        'total_page': total_page,
        'current_page': current_page
    }
    return jsonify(errno=RET.OK, errmsg="OK", data=data)


@news_blue.route('/<int:news_id>')
@login_required
def get_news_detail(news_id):
    user = g.user
    # 新闻点击排行
    try:
        news_list = News.query.order_by(News.clicks.desc()).limit(6)
    except Exception as e:
        current_app.logger.errno(e)
        return jsonify(errno=RET.DBERR, errmsg="查询新闻排行数据失败")
    if not news_list:
        return jsonify(errno=RET.DBERR, errmsg="无新闻排行数据")
    news_click_list = []
    for news in news_list:
        news_click_list.append(news.to_dict())
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.errno(e)
        return jsonify(errno=RET.DBERR, errmsg="查询新闻详情数据失败")
    if not news:
        return jsonify(errno=RET.NODATA, errmsg="无新闻详情数据")

    data = {
        'user_info': user.to_dict() if user else None,
        'news_click_list': news_click_list,
        'news_detail': news.to_dict()
    }
    return render_template('news/detail.html', data=data)


@news_blue.route('/favicon.ico')
def favicon():
    return current_app.send_static_file('news/favicon.ico')